const JWT = require('jsonwebtoken')
const { JWT_SECRET } = require('../config/config.default')
const { tokenExpiredError, jsonWebTokenError, notAdmin } = require('../constant/error.type')
const auth = async (ctx, next) => {
    //token认证
    const { authorization } = ctx.request.header
    
    const token = authorization.replace('Bearer ', '')
    // console.log(token);
    try {
        const emp = JWT.verify(token, JWT_SECRET)
        ctx.state.emp = emp
    } catch (err) {
        console.error(err);
        switch (err.name) {
            case 'TokenExpiredError':
                console.error('token已过期', err);
                ctx.app.emit('error', tokenExpiredError, ctx)
                break
            case 'JsonWebTokenError':
                console.error('token无效', err);
                ctx.app.emit('error', jsonWebTokenError, ctx)
                break
        }
        return
    }
    await next()
}

const verifyAdmin = async (ctx, next) => {

    const emp = ctx.state.emp
    if (emp.roleId !== 3) {
        ctx.app.emit('error', notAdmin, ctx)
        return
    }

    await next()
}

const verifyRole = async (ctx, next) => {

    const emp = ctx.state.emp
    if (emp.roleId === 0) {
        ctx.app.emit('error', notAdmin, ctx)
        return
    }

    await next()
}

module.exports = {
    auth,
    verifyAdmin,
    verifyRole,
}